import logging
from io import BytesIO

import pandas as pd
from django.contrib.auth.hashers import make_password

from apps.gupiaoliebiao.models import gupiaoliebiao
from apps.huicefenxi.models import huicefenxi, huicefenxi_data
from utils.common import formatdatetime
from utils.jsonResponse import ErrorResponse, DetailResponse
from utils.pagination import CustomPagination
from utils.serializers import CustomModelSerializer
from utils.viewset import CustomModelViewSet

logger = logging.getLogger(__name__)


# Create your views here.

# ================================================= #
# ************** 后端用户管理 view  ************** #
# ================================================= #

class huicefenxiManageSerializer(CustomModelSerializer):
    """
    用户管理-序列化器
    """

    class Meta:
        model = huicefenxi
        read_only_fields = ["id"]
        fields = '__all__'  # 显式包含所有字段


class huicefenxiDataManageSerializer(CustomModelSerializer):
    """
    用户管理-序列化器
    """

    class Meta:
        model = huicefenxi_data
        read_only_fields = ["id"]
        fields = '__all__'  # 显式包含所有字段


class huicefenxiManageCreateSerializer(CustomModelSerializer):
    """
    用户管理-序列化器
    """

    # 新增重写
    def create(self, validated_data):
        if "password" in validated_data.keys():
            if validated_data['password']:
                validated_data['password'] = make_password(validated_data['password'])
        validated_data['identity'] = 2
        return super().create(validated_data)

    class Meta:
        model = huicefenxi
        fields = '__all__'  # 显式包含所有字段
        read_only_fields = ["id"]
        # exclude = ['role', 'post', 'dept']
        # extra_kwargs = {
        #     'post': {'required': False},
        #     'role': {'required': False},
        #     'name': {'required': False},
        #     'password': {'required': False},
        # }


class huicefenxiViewSet(CustomModelViewSet):
    """
    后台用户管理 接口:
    """
    queryset = huicefenxi.objects.order_by("-create_datetime")  # 排除管理员
    serializer_class = huicefenxiManageSerializer
    create_serializer_class = huicefenxiManageCreateSerializer

    # filterset_fields = ('index_code', 'industry_name')
    # search_fields = ('index_code', 'industry_name',)

    # filterset_class = UsersManageTimeFilter
    def list_huicefenxi_data(self, request):
        huicefenxiId = request.GET.get('huicefenxiId')
        if not huicefenxiId:
            return ErrorResponse(msg='huicefenxiId为空')
        huicefenxi_data_list_result = huicefenxi_data.objects.filter(huicefenxi_id=huicefenxiId).all()

        # # 1. 实例化分页器对象
        page_obj = CustomPagination()
        # # 2. 使用自己配置的分页器调用分页方法进行分页
        page_data = page_obj.paginate_queryset(huicefenxi_data_list_result, request)
        data = []
        if huicefenxi_data_list_result:
            for q in page_data:
                data.append({
                    'pingzhongdaima': q.pingzhongdaima,
                    'pingzhongmingchen': q.pingzhongmingchen,
                    'yinglishu': q.yinglishu,
                    'zongcishu': q.zongcishu,
                    'shenglv': q.shenglv,  # True开启 False关闭
                    'shouxufei': q.shouxufei,
                    'jinlirun': q.jinlirun,
                    'shouyilv': q.shouyilv,
                    'nianhuashouyilv': q.nianhuashouyilv,
                    'xiangduishouyilv': q.xiangduishouyilv,
                    'zuidahuice': q.zuidahuice,
                    'zuidahuicebi': q.zuidahuicebi,
                    'l1_name': q.gupiaoliebiao_id.l1_name if q.gupiaoliebiao_id else '',
                    'l2_name': q.gupiaoliebiao_id.l2_name if q.gupiaoliebiao_id else '',
                    'l3_name': q.gupiaoliebiao_id.l3_name if q.gupiaoliebiao_id else '',
                    'create_datetime': formatdatetime(q.create_datetime),
                    'update_datetime': formatdatetime(q.update_datetime),

                })
        return page_obj.get_paginated_response(data)

    def create(self, request):
        file = request.FILES
        if not file:
            return ErrorResponse(msg='上传文件为空')
        df = pd.read_csv(
            BytesIO(file.get('upload').read()),
            encoding='gbk',  # 默认尝试 UTF-8
            engine='python',  # 避免 C 引擎的解析问题
            dtype=str,  # 统一读取为字符串避免类型错误
            sep='\t',
        )
        if df.empty:
            return ErrorResponse(msg='上传文件为空')
        data_row_df = df.iloc[1:]
        body_data = request.data.copy()
        body_data.pop('upload', None)

        save_data = huicefenxiManageSerializer(data=body_data)
        save_data.is_valid()
        save_data.save()
        huicefenxi_object = huicefenxi.objects.get(id=save_data.data.get('id'))
        for index, row in data_row_df.iterrows():
            gupiao = gupiaoliebiao.objects.filter(symbol=row['品种代码']).first()
            huicefenxi_data.objects.create(gupiaoliebiao_id=gupiao,
                                           huicefenxi_id=huicefenxi_object,
                                           pingzhongdaima=row['品种代码'],
                                           pingzhongmingchen=row["品种名称"],
                                           yinglishu=row["盈利数"],
                                           zongcishu=row["总次数"],
                                           shenglv=row["胜率(%)"],  # True开启 False关闭
                                           shouxufei=row["手续费(元)"],
                                           jinlirun=row["净利润(元)"],
                                           shouyilv=row["收益率(%)"],
                                           nianhuashouyilv=row["年化收益率(%)"],
                                           xiangduishouyilv=row["相对收益率α/β(%)"],
                                           zuidahuice=row["最大回撤(元)"],
                                           zuidahuicebi=row["最大回撤比(%)"])
            print(huicefenxi_data)
        return DetailResponse(data=None, msg="新增成功")

    # img_file = []
    # try:
    #     # 多图片上传，也可单图片
    #     for img in image:
    #         img_name = img.name
    #         # 图片类型content-type检查
    #         if not img.content_type.startswith('image/') and not img.content_type.startswith(
    #                 'video/') and not img.content_type.startswith('audio/'):
    #             msg['code'] = 400
    #             msg['msg'] = "请上传正确的文件格式"
    #             return msg
    #
    #         if not img_name.endswith(
    #                 ('.jpg', '.jpeg', '.png', 'gif', '.bmp', '.JPG', '.JPEG', '.PNG', 'GIF', '.BMP', '.mp4',
    #                  '.flv')):
    #             notimg_file.append(img_name)
    #
    #         if img.size > 1024 * 500000:
    #             msg['code'] = 400
    #             msg['msg'] = "图片大小不能超过500M"
    #             return msg
    #
    #         else:
    #             curr_time = datetime.datetime.now()
    #             image_name = renameuploadimg(img_name)
    #             time_path = curr_time.strftime("%Y-%m-%d")
    #             img_task_dir = dirs  # 对应models中的上传路径
    #             sub_path = os.path.join(settings.MEDIA_ROOT, img_task_dir, time_path)
    #             if not os.path.exists(sub_path):
    #                 os.makedirs(sub_path)
    #             image_path = os.path.join(sub_path, image_name)
    #             # web_img_url = settings.MEDIA_URL + img_task_dir + "/" + time_path + "/" + image_name#相对路径/media/xxx/xxxx/xxx.png
    #             web_img_url = DOMAIN_HOST + settings.MEDIA_URL + img_task_dir + "/" + time_path + "/" + image_name  # 绝对路径http://xxx.xxx.com/media/xxx/xxxx/xxx.png
    #             f = open(image_path, 'wb')
    #             for i in img.chunks():
    #                 f.write(i)
    #             f.close()
    #             img_file.append(web_img_url)
    #
    #     if notimg_file:
    #         msg['code'] = 400
    #         msg['msg'] = '请检查是否支持的文件，失败文件部分如下：{0}'.format(','.join(notimg_file[:10]))
    #         return msg
    #
    #     msg['code'] = 200
    #     msg['img'] = img_file  # ['/media/xxx/xxx/xxx.png']
    #     msg['msg'] = '上传成功'
    #     return msg
    #
    # except Exception as e:
    #     msg['code'] = 400
    #     msg['msg'] = '上传失败'
    #     return msg
    # result = ImageUpload(request, "frontendimages")
    # if result['code'] == 200:
    #     return SuccessResponse(data=result['img'], msg=result['msg'])
    # else:
    #     return ErrorResponse(msg=result['msg'])

# ================================================= #
# ************** 前端用户中心 view  ************** #
# ================================================= #


#
#
# class SetUserNicknameView(APIView):
#     """
#     修改昵称
#     post:
#     修改昵称
#     【参数】nickname:需要修改的用户新昵称
#     """
#     permission_classes = [IsAuthenticated]
#     authentication_classes = [JWTAuthentication]
#
#     # api文档参数
#
#     @swagger_auto_schema(operation_summary='app回收员修改昵称',
#                          # manual_parameters=[#GET请求需要
#                          #     # openapi.Parameter("nickname", openapi.IN_QUERY, description="要修改昵称", type=openapi.TYPE_STRING)
#                          # ],
#                          request_body=openapi.Schema(  # POST请求需要
#                              type=openapi.TYPE_OBJECT,
#                              required=['nickname'],
#                              properties={
#                                  'nickname': openapi.Schema(type=openapi.TYPE_STRING, description="要修改昵称"),
#                              },
#                          ),
#                          responses={200: 'success'},
#                          )
#     def post(self, request):
#         nickname = get_parameter_dic(request)['nickname']
#         if nickname is None:
#             return ErrorResponse(msg="昵称不能为空")
#         if not isinstance(nickname, str):
#             return ErrorResponse(msg='类型错误')
#         user = request.user
#         user.nickname = nickname
#         user.save()
#         return SuccessResponse(msg="success")
#
#
# # 前端app头像修改
# class ChangeAvatarView(APIView):
#     '''
#     前端app头像修改
#     post:
#     【功能描述】前端app头像修改</br>
#     【参数说明】无，需要登录携带token后才能调用</br>
#     '''
#     authentication_classes = [JWTAuthentication]
#     permission_classes = [IsAuthenticated]
#
#     def post(self, request, *args, **kwargs):
#         result = ImageUpload(request, "avatar")
#         if result['code'] == 200:
#             user = request.user
#             user.avatar = result['img'][0]
#             user.save()
#             return SuccessResponse(data=result['img'], msg=result['msg'])
#         else:
#             return ErrorResponse(msg=result['msg'])
#
#
# # 注销账号(标记已注销)
# class DestroyUserView(APIView):
#     '''
#     注销账号(标记已注销)
#     post:
#     【功能描述】注销账号(标记已注销)</br>
#     '''
#     authentication_classes = [JWTAuthentication]
#     permission_classes = [IsAuthenticated]
#
#     def post(self, request, *args, **kwargs):
#         user = request.user
#         if user.identity in [0, 1]:
#             return ErrorResponse(msg="该用户不支持注销")
#         if '(已注销)' in user.username:
#             return ErrorResponse(msg="该用户已注销或不支持注销")
#         with transaction.atomic():
#             randstr = getRandomSet(6)
#             user.username = user.username + "(已注销)" + randstr
#             user.mobile = user.mobile + "(已注销)" + randstr
#             user.is_delete = True
#             user.is_active = False
#             user.save()
#             OAuthWXUser.objects.filter(user=user).delete()
#             return SuccessResponse(data={}, msg="success")
#
#
# # 前端APP下载页面
# def downloadapp(request):
#     return render(request, "download-app/index.html")
